import { createSlice } from "@reduxjs/toolkit"
import axios from "axios"

const billStore = createSlice({
  name: 'bill',
  initialState: {
    billList: []
  },
  reducers: {
    // 同步修改方法
    setBillList (state, action) {
      state.billList = action.payload
    },
    addBillList (state, action) {
      state.billList.push(action.payload)
    }
  }
})

const { setBillList, addBillList } = billStore.actions

// 异步修改方法

// 获取账单列表
const getBillList = () => {
  return async (dispatch) => {
    const res = await axios.get('http://localhost:8888/ka')
    dispatch(setBillList(res.data))
  }
}
// 新增账单
const addBill = (data) => {
  return async (dispatch) => {
    const res = await axios.post('http://localhost:8888/ka', data)
    dispatch(addBillList(res.data))
  }
}

// 导出异步修改方法
export { getBillList, addBill }

// 导出 reducer
const billReducer = billStore.reducer

export default billReducer